// 企业邀请: 邀请加入企业
const { addInvite, getInviteList, getInviteInfo, updateInvite } = require('../../model/invite')
const { getMemberInfoById } = require('../../model/member')


// 获取邀请列表数据:受邀账号
const inviteList = async (req, res) => {
    const output = { code: 200, msg: '操作成功' }
    const { page, size } = req.query
    // 获取登录账号id
    const { id: invited_uid } = req.loginInfo
    const map = { invited_uid }
    if (page && size) {
        map.page = page
        map.size = size
    }
    const result = await getInviteList(map)
    output.data = result
    res.send(output)
}

// 获取邀请详情数据:受邀账号
const inviteInfo = async (req, res) => {
    const output = { code: 200, msg: '操作成功' }
    const { id } = req.query
    if (!id) {
        output.code = 500
        output.msg = '参数错误:缺少参数id'
        return res.send(output)
    }
    const result = await getInviteInfo({ id })
    output.data = result
    res.send(output)
}

// 发出邀请
const inviteAdd = async (req, res) => {
    const output = {
        code: 200, msg: "操作成功"
    }
    // 获取当前登录账号id, 即邀请发出方账号id
    const { id: invite_uid } = req.loginInfo
    // 受邀方账号id
    const { invited_uid } = req.body
    if (invite_uid === invited_uid) {
        output.code = 500
        output.msg = '系统错误:邀请者和受邀者账号不能相同'
        return res.send(output)
    }

    const { account_type: invite_account_type, bus_id: invite_bus_id } = await getMemberInfoById(invite_uid)

    // 只有企业管理员账号可以向普通账号发出加入要求
    if (invite_account_type >= 3 && !invite_bus_id) {
        output.code = 500
        output.msg = '系统错误:只有企业管理员账号可以向普通账号发出加入要求'
        return res.send(output)
    }
    const { account_type: invited_account_type, bus_id: invited_bus_id } = await getMemberInfoById(invited_uid)
    // 受邀方必须是普通账号类型, 否则无法被邀请, 受邀方必须主动退出之前的企业, 方能被邀请
    if (invited_account_type >= 2 || invited_bus_id > 0) {
        output.code = 500
        output.msg = '系统错误:受邀方必须是普通账号类型, 否则无法被邀请, 受邀方必须主动退出之前的企业, 方能被邀请'
        return res.send(output)
    }
    const result = await addInvite(invite_uid, invited_uid)
    output.data = { insertId: result.insertId }
    res.send(output)
}

// 接受或者拒绝邀请
const inviteUpdate = async (req, res) => {
    const output = {
        code: 200, msg: "操作成功"
    }
    const { id, invite_status } = req.body
    if (!id || ![2, 3].includes(invite_status)) {
        output.code = 500
        output.msg = "参数错误: 缺少id,invite_status(参数值必须是2接受邀请或3拒绝邀请)"
        return res.send(output)
    }
    const result = await updateInvite(id, invite_status)
    output.data = { changedRows: result.changedRows }
    res.send(output)
}
// 删除邀请
const inviteRemove = async (req, res) => {
    const output = {
        code: 200, msg: "操作成功"
    }
    const { id } = req.query
    if (!id) {
        output.code = 500
        output.msg = "参数错误: 缺少参数id"
        return res.send(output)
    }
    res.send(output)
}

module.exports = {
    inviteAdd,
    inviteList,
    inviteInfo,
    inviteUpdate,
    inviteRemove
}
